import React, { useRef, useState } from 'react';
import { flushSync } from 'react-dom';
import { PlusOutlined, MinusOutlined } from '@ant-design/icons';
import { ModalForm, PageContainer, ProFormText, ProTable, ProFormUploadButton } from '@ant-design/pro-components';
import { Button, message, Image, Popconfirm,Space} from 'antd';
import errorImage from '@/assets/error.png';
import _ from '@/assets/utils';
import MODEL_API from '@/services/model';
import styled from 'styled-components';
import { history, useSearchParams, useModel, Helmet } from '@umijs/max';
import { ArrowLeftOutlined } from '@ant-design/icons';
const RightStyle = styled.div`
    .ant-pro-table-list-toolbar-right   {
  margin-right: 1100px;
}
.ant-page-header {
  position: relative;
  height: 80px;
  .ant-page-header-heading-title {
    position: absolute;
    top: 22px;
    left: 77px;
  }
  .ant-space {
    position: absolute;
    top: 25px;
    left: 52px;
    font-size:19px;
  }
}
`;
const level2 = function level2() {
  const columns = [{
    title: '分类名称',
    dataIndex: 'categoryName',
    width: '50%',
  }, {
    title: '排序值',
    dataIndex: 'categoryRank',
    width: '10%',
  }, {
    title: '添加时间',
    dataIndex: 'createTime',
    width: '20%',
    render: (dom) => {
      if (!dom) return '--';
      return _.formatTime(dom, '{0}-{1}-{2}');
    }
  }, {
    title: '操作',
    width: '20%',
    render: (_, record) => {
      let { categoryId, categoryName, categoryRank, categoryLevel } = record;
      return [
        <Popconfirm key="delete" title="确定要删除这条记录吗？"
          onConfirm={() => {
            handleRemove([categoryId]);
          }}>
          <a href="#">删除</a>
        </Popconfirm>,
        <Button key="classify" type="link"
          onClick={() => {
            history.push({
              pathname: '/modulars/Classify/level3',
              query: {
                level: categoryLevel + 1,
                parent_id: categoryId
              }
            });
          }}>
          下级分类
        </Button>,
        <Button key="update" type="link"
          onClick={() => {
            // 防止第一次加载组件，直接点击修改，如果按照异步操作，ModelForm还没有渲染解析，我们是获取不到实例信息的
            flushSync(() => {
              setModelVisible(true);
              setCategoryId(categoryId);
            })
            // 给Form内部的三个字段赋值
            modelFormIns.current.setFields([{
              name: 'categoryName',
              value: categoryName
            }, {
              name: 'categoryRank',
              value: categoryRank
            }]);
          }}>
          修改
        </Button>
      ];
    }
  }];
  const [modelVisible, setModelVisible] = useState(false),//弹model框
    [categoryId, setCategoryId] = useState(null),//判断新增还是修改
    // [categoryLevel, setCategoryLevel] = useState(1),
    // [parentId, setParentId] = useState(0),
    [selectList, setSelectList] = useState([]),//存批量选中的id
    [] = useState([]),
    modelFormIns = useRef(),//清除model里数据要拿到他的dom元素
    tableIns = useRef(); //刷新页面的
    const [usp] = useSearchParams();
  /* 表格数据的处理 */
  let level = usp.get('level');
  let parent_id = usp.get('parent_id');
  const queryTableData = async ({ pageSize, current, categoryLevel=level, parentId=parent_id }) => {
    let tableData = [],
      total = 0;
    try {
      let { resultCode, data } = await MODEL_API.classifyList(current, pageSize, categoryLevel, parentId);
      if (+resultCode === 200) {
        total = +data.totalCount;
        tableData = data.list;
      }
    } catch (_) { }
    // 不论请求成功还是失败，都让表格进行渲染
    return {
      success: true,
      data: tableData,
      total
    };
  };
  /* 提交信息 */
  const submit = async (values) => {
    let requestFunc = MODEL_API.classifyInsert,
      tip = '新增';
    values.categoryLevel = level;
    values.parentId = parent_id;
    if (categoryId) {
      requestFunc = MODEL_API.classifyUpdate;
      tip = '修改';
      values.categoryId = categoryId;
      values.parentId = parent_id;
    }
    try {
      let { resultCode } = await requestFunc(values);
      if (+resultCode !== 200) {
        message.error(`很遗憾，${tip}失败了，请稍后再试~`);
        return;
      }
      message.success(`恭喜您，${tip}成功！`);
      modelOpenChange(false);
      tableIns.current.reload();
    } catch (_) { }
  };
  const handleRemove = async (ids) => {
    try {
      let { resultCode,message:sb } = await MODEL_API.classifyRemove(ids);
      if (+resultCode !== 200) {
        message.error(sb);
        return;
      }
      message.error('恭喜您，删除成功！');
      tableIns.current.reload();
    } catch (_) { }
  };
  /* Model关闭后要干什么 */
  const modelOpenChange = (bool) => {
    if (bool) return;
    setModelVisible(false);
    setCategoryId(null);
    modelFormIns.current.resetFields();
  };
  const ggg=()=>{
    history.back()
  }
  return <RightStyle>
  <PageContainer content={<Space><ArrowLeftOutlined onClick={ggg}/></Space>}>
    <ProTable
      request={queryTableData}
      columns={columns}
      search={false}
      options={{
        density: false,
        reload: false,
        setting: false
      }}
      pagination={{
        pageSize: 10,
        hideOnSinglePage: false,
        showTotal: false,
        showQuickJumper: false,
        showSizeChanger: false
      }}
      toolBarRender={() => {
        return [
          <Button key="new" type="primary"
            onClick={() => setModelVisible(true)}
          >
            <PlusOutlined /> 新增
          </Button>,

          <Button key="delete" type="primary" danger
            onClick={async () => {
              if (selectList.length === 0) {
                message.warning('请至少选择一项进行删除~');
                return;
              }
              await handleRemove(selectList);
            }}
          >
            <MinusOutlined /> 批量删除
          </Button>
        ];
      }}
      actionRef={tableIns}
      rowKey="categoryId"
      rowSelection={{
        onChange: (selectedIds) => setSelectList(selectedIds)
      }}
    />

    <ModalForm
      title={`${categoryId ? '修改' : '添加'}商品`}
      width="500px"
      layout='horizontal'
      open={modelVisible}
      onOpenChange={modelOpenChange}
      labelCol={{ span: 5 }}
      validateTrigger="onBlur"
      initialValues={{
        carouselUrl: '',
        carouselRank: '',
        redirectUrl: ''
      }}
      formRef={modelFormIns}
      onFinish={submit}
    >
      <ProFormText
        label="分类名称"
        name="categoryName"
        placeholder=""
        rules={[
          { required: true, message: '名称不能为空' }
        ]}
      />

      <ProFormText
        label="排序值"
        name="categoryRank"
        placeholder=""
        rules={[
          { required: true, message: '排序不能为空' }
        ]}
      />
    </ModalForm>
  </PageContainer>
  </RightStyle>
}
export default level2;
